package com.xx.track_log.log;

import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author fanjj
 * @date 2017/10/19
 */
public class LoggingEventProcessor {
    private boolean hold = true;
    private Writer writer;
    List<LoggingEvent> events = new ArrayList<>();
    private String logFolder;
    private String actionName;
    private String logLevel;

    public LoggingEventProcessor(String logFolder, String actionName, String logLevel) {
        this.logFolder = logFolder;
        this.actionName = actionName;
        this.logLevel = logLevel;
    }

    public void process(LoggingEvent event, Layout layout) {
        if (hold) {
            events.add(event);
            if (needFlush(event)) { // flushTraceLogs and write to file until level greater equal than error, then always write to file.
                flushTraceLogs(layout);
                hold = false;
            }
        } else {
            write(event, layout);
        }
    }

    public boolean needFlush(LoggingEvent event) {
        return event.getLevel().isGreaterOrEqual(Level.toLevel(logLevel));
    }

    public void flushTraceLogs(Layout layout) {
        if (writer == null)
            createWriter();
        for (LoggingEvent event : events) {
            write(event, layout);
        }
        events.clear(); // clear events when error | warning happened ,write to log directly next time.
    }

    private void write(LoggingEvent event, Layout layout) {
        try {
            writer.write(layout.format(event));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void createWriter() {
        try {
            File logFile = generateLogFolder();
            createParentFolder(logFile);
            writer = new BufferedWriter(new FileWriter(logFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void createParentFolder(final File logFile) {
        logFile.getParentFile().mkdirs();
    }

    private File generateLogFolder() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String sequence = String.format("%0" + 5 + "d", new Random().nextInt(99999));
        return new File(String.format("%s/%s/%s/%s%s.log", logFolder, sdf.format(date), actionName, sdf2.format(date), sequence));
    }

    public void cleanup() {
        if (logFolder != null && writer != null) {
            try {
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
